import hre from "hardhat";
import fs from 'fs';

const { ethers } = hre;

async function main() {
    console.log("🌉 开始部署跨链拍卖系统...\n");

    const [deployer] = await ethers.getSigners();
    console.log("📋 部署账户:", deployer.address);

    const balance = await ethers.provider.getBalance(deployer.address);
    console.log("💰 账户余额:", ethers.formatEther(balance), "ETH\n");

    // 网络配置
    const network = await ethers.provider.getNetwork();
    console.log("🌐 部署网络:", network.name, "Chain ID:", network.chainId);

    // CCIP 路由器地址（根据网络配置）
    const ccipRouters = {
        11155111: "0x0BF3dE8c5D3e8A2B34D2BEeB17ABfCeBaf363A59", // Ethereum Sepolia
        80001: "0x70499c328e1E2a3c41108bd3730F6670a44595D1",    // Polygon Mumbai
        43113: "0x554472a2720E5E7D5D3C817529aBA05EEd5F82D8"     // Avalanche Fuji
    };

    const routerAddress = ccipRouters[network.chainId.toString()];

    if (!routerAddress) {
        console.log("⚠️  当前网络不支持CCIP，使用模拟路由器进行本地测试");

        // 部署模拟路由器
        console.log("🔧 部署模拟CCIP路由器...");
        const MockRouter = await ethers.getContractFactory("MockCCIPRouter");
        const mockRouter = await MockRouter.deploy();
        await mockRouter.waitForDeployment();

        console.log("✅ 模拟路由器已部署:", mockRouter.target);
        routerAddress = mockRouter.target;
    } else {
        console.log("🔗 使用CCIP路由器:", routerAddress);
    }

    try {
        // 1. 部署SimpleCrossChainAuction
        console.log("\n🌉 部署SimpleCrossChainAuction合约...");
        const SimpleCrossChainAuction = await ethers.getContractFactory("SimpleCrossChainAuction");
        const crossChainAuction = await SimpleCrossChainAuction.deploy(routerAddress);
        await crossChainAuction.waitForDeployment();

        console.log("✅ SimpleCrossChainAuction已部署:", crossChainAuction.target);

        // 2. 部署测试NFT（可选）
        console.log("\n🎨 部署测试NFT合约...");
        const MockERC721 = await ethers.getContractFactory("MockERC721");
        const testNFT = await MockERC721.deploy("CrossChain Test NFT", "CCNFT");
        await testNFT.waitForDeployment();

        console.log("✅ 测试NFT已部署:", testNFT.target);

        // 3. 配置支持的链
        console.log("\n🔗 配置支持的区块链...");

        const supportedChains = [
            { name: "Ethereum Sepolia", selector: "5009297550715157269" },
            { name: "Polygon Mumbai", selector: "4051577828743386545" },
            { name: "Avalanche Fuji", selector: "6433500567565415381" }
        ];

        for (const chain of supportedChains) {
            try {
                const tx = await crossChainAuction.addSupportedChain(chain.selector);
                await tx.wait();
                console.log(`✅ 已添加支持链: ${chain.name} (${chain.selector})`);
            } catch (error) {
                console.log(`⚠️  添加链失败 ${chain.name}:`, error.message);
            }
        }

        // 4. 铸造测试NFT
        console.log("\n🎨 铸造测试NFT...");
        const mintTx = await testNFT.mint(deployer.address, 1);
        await mintTx.wait();
        console.log("✅ 已铸造NFT #1 给部署者");

        // 5. 初始化测试拍卖
        console.log("\n🎯 初始化测试拍卖...");
        const startPrice = ethers.parseEther("0.1");
        const duration = 3600; // 1小时

        const initTx = await crossChainAuction.initializeAuction(
            testNFT.target,
            1,
            deployer.address,
            startPrice,
            duration
        );
        await initTx.wait();

        console.log("✅ 测试拍卖已初始化");
        console.log("   NFT合约:", testNFT.target);
        console.log("   Token ID: 1");
        console.log("   起始价格:", ethers.formatEther(startPrice), "ETH");
        console.log("   持续时间:", duration / 60, "分钟");

        // 6. 显示部署总结
        console.log("\n" + "=".repeat(60));
        console.log("🎉 跨链拍卖系统部署完成！");
        console.log("=".repeat(60));
        console.log("📋 部署信息:");
        console.log("   网络:", network.name);
        console.log("   链ID:", network.chainId);
        console.log("   部署者:", deployer.address);
        console.log("   CCIP路由器:", routerAddress);
        console.log("\n📦 合约地址:");
        console.log("   SimpleCrossChainAuction:", crossChainAuction.target);
        console.log("   测试NFT:", testNFT.target);

        console.log("\n🔗 支持的链:");
        supportedChains.forEach(chain => {
            console.log(`   ✅ ${chain.name}`);
        });

        console.log("\n🚀 下一步操作:");
        console.log("   1. 验证合约: npx hardhat verify", crossChainAuction.target, routerAddress);
        console.log("   2. 运行测试: npx hardhat test");
        console.log("   3. 与合约交互: npx hardhat run scripts/interact-crosschain.js");

        // 保存部署信息
        const deploymentInfo = {
            network: network.name,
            chainId: network.chainId.toString(),
            deployer: deployer.address,
            timestamp: new Date().toISOString(),
            contracts: {
                SimpleCrossChainAuction: crossChainAuction.target,
                TestNFT: testNFT.target,
                CCIPRouter: routerAddress
            },
            supportedChains: supportedChains,
            testAuction: {
                nftContract: testNFT.target,
                tokenId: 1,
                startPrice: ethers.formatEther(startPrice),
                duration: duration
            }
        };

        // 保存到文件
        const deploymentFile = `deployments/crosschain-${network.name}-${Date.now()}.json`;

        if (!fs.existsSync('deployments')) {
            fs.mkdirSync('deployments');
        }

        fs.writeFileSync(deploymentFile, JSON.stringify(deploymentInfo, null, 2));
        console.log("\n💾 部署信息已保存到:", deploymentFile);

        return {
            crossChainAuction: crossChainAuction.target,
            testNFT: testNFT.target,
            router: routerAddress
        };

    } catch (error) {
        console.error("\n❌ 部署失败:", error);
        throw error;
    }
}

// 错误处理
main()
    .then((result) => {
        console.log("\n🎊 部署成功完成！");
        process.exit(0);
    })
    .catch((error) => {
        console.error("💥 部署过程出错:", error);
        process.exit(1);
    });
